import os
import cv2
import numpy as np
import json

def cv_imread(img_path):
    """读取包含中文路径的图片"""
    with open(img_path, 'rb') as f:
        img_array = np.frombuffer(f.read(), dtype=np.uint8)
        return cv2.imdecode(img_array, cv2.IMREAD_COLOR)

def cv_imwrite(output_path, image):
    """保存图片到中文路径"""
    _, img_encoded = cv2.imencode('.jpg', image)
    with open(output_path, 'wb') as f:
        f.write(img_encoded)

def crop_and_save_images(label_file):
    # 处理Label.txt文件
    with open(label_file, 'r', encoding='utf-8') as f:
        label_lines = f.readlines()
    
    for line in label_lines:
        if line.strip():
            parts = line.split('\t')
            if len(parts) == 2:
                img_path = parts[0]
                json_data = parts[1].strip()
                
                # 解析JSON数据获取坐标点
                try:
                    data = json.loads(json_data)
                    for i, item in enumerate(data):
                        points = item['points']
                        # 读取图片并裁剪
                        img = cv_imread(img_path)
                        x_coords = [p[0] for p in points]
                        y_coords = [p[1] for p in points]
                        x_min, x_max = min(x_coords), max(x_coords)
                        y_min, y_max = min(y_coords), max(y_coords)
                        cropped_img = img[y_min:y_max, x_min:x_max]
                        
                        # 保存裁剪后的图片，添加序号
                        base_name = os.path.splitext(os.path.basename(img_path))[0]
                        output_path = f"crop_img/{base_name}_crop_{i}.jpg"
                        cv_imwrite(output_path, cropped_img)
                except Exception as e:
                    print(f"Error processing {img_path}: {e}")
    
    # 修改为写入新文件，并优化文件处理
    with open('rec_gt_new.txt', 'w', encoding='utf-8') as gt_file:
        for line in label_lines:
            if line.strip():
                parts = line.split('\t')
                if len(parts) == 2:
                    img_path = parts[0]
                    json_data = parts[1].strip()
                    
                    try:
                        data = json.loads(json_data)
                        for i, item in enumerate(data):
                            transcription = item['transcription']
                            new_img_name = os.path.splitext(os.path.basename(img_path))[0] + f"_crop_{i}.jpg"
                            relative_path = f"crop_img/{new_img_name}"
                            gt_file.write(f"{relative_path}\t{transcription}\n")
                    except Exception as e:
                        print(f"Error processing {img_path}: {e}")

# 创建crop_img文件夹
os.makedirs('crop_img', exist_ok=True)
crop_and_save_images('Label.txt')